// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package badger_dao_impl

import (
	"context"
	"fmt"
	"path/filepath"
	"sort"
	"strings"

	"gitcode.com/openseaotter/so_proto_gen_go.git/watch_api"
	"gitcode.com/openseaotter/so_server/storage/core"
	"gitcode.com/openseaotter/so_server/utils"
	"github.com/dgraph-io/badger/v4"
	"google.golang.org/protobuf/proto"
)

type ChangeInfoList []*watch_api.ChangeInfo

func (a ChangeInfoList) Len() int           { return len(a) }
func (a ChangeInfoList) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ChangeInfoList) Less(i, j int) bool { return a[i].TimeStamp < a[j].TimeStamp }

type _ChangeDao struct {
	dbh *badger.DB
}

func NewChangeDao() (core.ChangeDao, error) {
	dbPath := filepath.Join(utils.DATA_DIR_PATH, "change")
	options := badger.DefaultOptions(dbPath)
	dbh, err := badger.Open(options)
	if err != nil {
		return nil, err
	}
	return &_ChangeDao{dbh: dbh}, nil
}

func (db *_ChangeDao) genKey(watchId, changeId string) string {
	return strings.Join([]string{watchId, changeId}, "\t")
}

func (db *_ChangeDao) genKeyPrefix(watchId string) string {
	return fmt.Sprintf("%s\t", watchId)
}

func (db *_ChangeDao) Insert(ctx context.Context, info *watch_api.ChangeInfo) error {
	txn := db.dbh.NewTransaction(true)
	defer txn.Discard()

	key := db.genKey(info.WatchId, info.ChangeId)
	value, err := proto.Marshal(info)
	if err != nil {
		return err
	}
	err = txn.Set([]byte(key), value)
	if err != nil {
		return err
	}
	return txn.Commit()
}

func (db *_ChangeDao) Get(ctx context.Context, watchId, changeId string) (*watch_api.ChangeInfo, error) {
	txn := db.dbh.NewTransaction(false)
	defer txn.Discard()

	key := db.genKey(watchId, changeId)
	item, err := txn.Get([]byte(key))
	if err != nil {
		return nil, err
	}
	if item.IsDeletedOrExpired() {
		return nil, badger.ErrKeyNotFound
	}
	value, err := item.ValueCopy(nil)
	if err != nil {
		return nil, err
	}
	retInfo := &watch_api.ChangeInfo{}
	err = proto.Unmarshal(value, retInfo)
	if err != nil {
		return nil, err
	}
	return retInfo, nil
}

func (db *_ChangeDao) Count(ctx context.Context, watchId string) (uint32, error) {
	txn := db.dbh.NewTransaction(false)
	defer txn.Discard()

	keyPrefix := db.genKeyPrefix(watchId)
	options := badger.IteratorOptions{
		PrefetchValues: false,
		PrefetchSize:   100,
		Reverse:        false,
		AllVersions:    false,
		Prefix:         []byte(keyPrefix),
	}
	iter := txn.NewIterator(options)
	defer iter.Close()

	retCount := uint32(0)
	for iter.Rewind(); iter.Valid(); iter.Next() {
		item := iter.Item()
		if item.IsDeletedOrExpired() {
			continue
		}
		retCount += 1
	}
	return retCount, nil
}

func (db *_ChangeDao) List(ctx context.Context, watchId string) ([]*watch_api.ChangeInfo, error) {
	txn := db.dbh.NewTransaction(false)
	defer txn.Discard()

	keyPrefix := db.genKeyPrefix(watchId)
	options := badger.IteratorOptions{
		PrefetchValues: true,
		PrefetchSize:   100,
		Reverse:        false,
		AllVersions:    false,
		Prefix:         []byte(keyPrefix),
	}
	iter := txn.NewIterator(options)
	defer iter.Close()

	changeList := []*watch_api.ChangeInfo{}
	for iter.Rewind(); iter.Valid(); iter.Next() {
		item := iter.Item()
		if item.IsDeletedOrExpired() {
			continue
		}
		value, err := item.ValueCopy(nil)
		if err != nil {
			return nil, err
		}
		info := &watch_api.ChangeInfo{}
		err = proto.Unmarshal(value, info)
		if err != nil {
			return nil, err
		}
		changeList = append(changeList, info)
	}

	sort.Sort(sort.Reverse(ChangeInfoList(changeList)))
	return changeList, nil
}

func (db *_ChangeDao) RemoveByWatch(ctx context.Context, watchId string) error {
	txn := db.dbh.NewTransaction(true)
	defer txn.Discard()

	keyPrefix := db.genKeyPrefix(watchId)
	options := badger.IteratorOptions{
		PrefetchValues: false,
		PrefetchSize:   100,
		Reverse:        false,
		AllVersions:    false,
		Prefix:         []byte(keyPrefix),
	}
	iter := txn.NewIterator(options)
	defer iter.Close()

	keyList := [][]byte{}

	for iter.Rewind(); iter.Valid(); iter.Next() {
		item := iter.Item()
		if item.IsDeletedOrExpired() {
			continue
		}
		key := item.KeyCopy(nil)
		keyList = append(keyList, key)
	}

	iter.Close()

	for _, key := range keyList {
		err := txn.Delete(key)
		if err != nil {
			return err
		}
	}

	return txn.Commit()
}
